package com.sjtu.bookread;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.sjtu.bookread.myRecyclerview.MyRecyclerViewAdapter;
import com.sjtu.bookread.myRecyclerview.MyViewHolder;
import com.sjtu.bookread.obj.BookListObj;
import com.sjtu.bookread.obj.BookObj;
import com.sjtu.bookread.obj.BookObj1;
import com.sjtu.bookread.obj.SearchResultObj;
import com.sjtu.bookread.service.BookService;
import com.sjtu.bookread.service.RecomService;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static com.sjtu.bookread.control.DatabaseControl.getInstance;
import static com.sjtu.bookread.service.BookService.getBookService;


public class SearchActivity extends AppCompatActivity {

    private SearchView searchView;
    private TextView cancelView;
    private ListView fuzzyList;
    private LinearLayout searchLayout;
    private RecyclerView resultList;
    private List<BookObj1> results;
    private MyRecyclerViewAdapter recyclerViewAdapter;
    private boolean isSubmit;
    private boolean flag;
    public Handler handler = new Handler();


    // 辅助函数：判断网络是否连接
    public boolean isNetWorkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isConnected();
            }
        }
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        changeStatusIconCollor(true);
        Window window =this.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(ContextCompat.getColor(this,R.color.colorGreyTitle));

        setContentView(R.layout.activity_search);
        isSubmit = false;
        flag = true; //用于同步问题的布尔变量
        //初始化列表
        results = new ArrayList<>();
        //获取控件
        cancelView = findViewById(R.id.search_cancel_text);
        searchView = findViewById(R.id.search_search_searchView);

        fuzzyList = findViewById(R.id.search_fuzzy_list);
        resultList = findViewById(R.id.search_result_list);

        searchLayout = findViewById(R.id.search_afters_layout);

        //设置结果列表adapter
        recyclerViewAdapter = new MyRecyclerViewAdapter<BookObj1>(SearchActivity.this,R.layout.item_book,results) {
            @Override
            public void convert(MyViewHolder holder, final BookObj1 book) {
                TextView name = holder.getView(R.id.item_book_name);
                name.setText(book.getTitle());

                TextView author = holder.getView(R.id.item_book_author);
                author.setText(book.getAuthor());

                TextView major = holder.getView(R.id.item_book_type);
                major.setText(book.getCate());

                TextView intro = holder.getView(R.id.item_book_intro);
                String introString = book.getShortIntro();
                if (introString.length() > 50){
                    introString = introString.substring(0,49)+"……";
                }
                intro.setText(introString);

                final ImageView cover = holder.getView(R.id.item_book_cover);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (isNetWorkConnected(MainActivity.getContext())) {
                                URL url = new URL(RecomService.ApiUrl + "/"+ book.getCover());
                                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                                connection.setRequestMethod("GET");
                                connection.setConnectTimeout(10000);
                                if (connection.getResponseCode() == 200) {
                                    InputStream inputStream = connection.getInputStream();
                                    final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            cover.setImageBitmap(bitmap);
                                        }
                                    });
                                }
                            }
                            else{
                                Looper.prepare();
                                Toast.makeText(SearchActivity.this,"网络似乎出现了点问题",Toast.LENGTH_SHORT).show();
                                Looper.loop();
                            }
                        } catch (Exception e) {
                            System.err.println(e.getMessage());
                        }
                    }
                }).start();
            }
        };
        recyclerViewAdapter.setOnItemClickListener(new MyRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onClick(final int position) {
                final Intent intent = new Intent(SearchActivity.this, BookDetailActivity.class);
                final Bundle bundle = new Bundle();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (isNetWorkConnected(MainActivity.getContext())) {
                            final BookObj1 t = RecomService.getRecomService().getBook(results.get(position).getId());
                            if (t != null)
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        bundle.putSerializable("bookobj", t);
                                        intent.putExtras(bundle);
                                        startActivity(intent);
                                    }
                                });
                        }
                        else {
                            Looper.prepare();
                            Toast.makeText(SearchActivity.this,"网络似乎出现了点问题",Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }
                    }
                }).start();
            }

            @Override
            public void onLongClick(int position) {

            }
        });
        resultList.setAdapter(recyclerViewAdapter);
        resultList.setLayoutManager(new LinearLayoutManager(this));

        //设置搜索函数
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(final String s) {
                isSubmit = true;

                //设置可见
                searchLayout.setVisibility(View.VISIBLE);
                fuzzyList.setVisibility(View.GONE);
                resultList.setVisibility(View.VISIBLE);
                //填充数据
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (isNetWorkConnected(MainActivity.getContext())) {
                            boolean specialFlag = false;
                            String bookIdStr = "";
                            if (s.startsWith("[图书分享]")) {
                                String[] ans = s.split("\n");
                                String result = ans[ans.length-1];
                                if (result.startsWith("<--|") && result.endsWith("|-->")) {
                                    bookIdStr = result.substring(4, result.length()-4);
                                    specialFlag = true;
                                }
                            }

                            BookListObj bookListObj;
                            if (specialFlag) {
                                bookListObj = RecomService.getRecomService().getSpecialSearchBookList(bookIdStr);
                            }
                            else {
                                bookListObj = RecomService.getRecomService().getSearchBookList(s);
                            }
                            results.clear();
                            if (bookListObj != null && bookListObj.isOk()) {
                                List<BookObj1> t = bookListObj.getBooks();
                                results.addAll(t);
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        recyclerViewAdapter.notifyDataSetChanged();
                                    }
                                });
                            }
                            else {
                                Looper.prepare();
                                Toast.makeText(SearchActivity.this,"搜索不到相关内容",Toast.LENGTH_SHORT).show();
                                Looper.loop();
                            }
                        }
                        else {
                            Looper.prepare();
                            Toast.makeText(SearchActivity.this,"网络似乎出现了点问题",Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }
                    }
                }).start();
                recyclerViewAdapter.notifyDataSetChanged();
                return false;
            }

            @Override
            public boolean onQueryTextChange(final String s) {
                //设置可见
                if (!isSubmit) {
                    if (s.equals("")) {
                        searchLayout.setVisibility(View.GONE);
                    }
                    else {
                        searchLayout.setVisibility(View.VISIBLE);
                        fuzzyList.setVisibility(View.VISIBLE);
                        resultList.setVisibility(View.GONE);
                    }
                }
                else {
                    if (s.equals("")) {
                        fuzzyList.setVisibility(View.GONE);
                        resultList.setVisibility(View.VISIBLE);
                    }
                    else {
                        fuzzyList.setVisibility(View.VISIBLE);
                        resultList.setVisibility(View.GONE);
                    }
                }

                return false;
            }
        });


        //取消按钮点击事件
        cancelView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    public void changeStatusIconCollor(boolean setDark) {
        View decorView = getWindow().getDecorView();
        if(decorView != null){
            int vis = decorView.getSystemUiVisibility();
            if(setDark){
                vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            } else{
                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            }
            decorView.setSystemUiVisibility(vis);
        }
    }

}
